//
//  RouteViewController.m
//  DigiOps
//
//  Created by app on 2018/7/17.
//  Copyright © 2018年 jackyu. All rights reserved.
//

#import "RouteViewController.h"
#import "RouteViewCell.h"
#import "SopViewController.h"
#import "lhScanQCodeViewController.h"
#import "DetailViewController.h"
#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "XTAlertView.h"
#import "SopNoticeViewController.h"
#import "UserSites.h"
#import "RouteModel.h"
#import "LineDetail.h"
#import "LineDetailOffline.h"
#import "contentListLine.h"
#import "pointList.h"
#import "sopList.h"
#import "PointModel.h"
#import "PointValueModel.h"
#import "MyBarCodeController.h"
#import "HomeViewController.h"
#import "pictureData.h"
#import "SopModel.h"

@interface RouteViewController ()<UITableViewDelegate,UITableViewDataSource,XTAlertControllerDelegate,SopRouteDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *routeArray;
@property(nonatomic, strong)NSMutableArray *exceptionArray;

@property(nonatomic, assign)NSInteger pageSize;
@property(nonatomic, assign)NSInteger pageIndex;

@property(strong,nonatomic)UIWindow *window;
@property(strong,nonatomic)UIButton *button;
@property(strong,nonatomic)UILabel* lineLabel;

@property(nonatomic, strong)NSMutableArray *soprouteArray;
@property(nonatomic,strong)RouteModel* routeModelc;//当前路线模型
@property(nonatomic,assign) int rejectCount;

@property(nonatomic, strong)NSString* lineUuid;
@property(nonatomic,assign)BOOL okSubmit;
@property(nonatomic,assign)NSString* refuseRemark;
//
@property(nonatomic,assign)UIImageView* arrow;
@property(nonatomic,assign)UILabel* helplabel;


@end

@implementation RouteViewController
static RouteViewController *rvc = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        rvc = [[self alloc] init];
    });
    return rvc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.rejectCount=1;
    self.pageSize = 20;
    self.pageIndex = 1;
    self.routeArray = [NSMutableArray array];
    self.soprouteArray=[NSMutableArray array];
    self.exceptionArray=[NSMutableArray array];
    
    [self.view addSubview:self.tableView];
    
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"巡逻";
    self.navigationItem.titleView = label;
    
    /** MJRefresh的block也需要用若引用 */
    WEAKSELF
//    self.tableView.mj_header = [XMRefreshHeader xm_headerWithRefreshingBlock:^{
//        self.pageIndex = 1;
////        [self.routeArray removeAllObjects];//移除数据内容可以崩溃
////        [weakSelf searchAticle];
//    }];
    //默认block方法：设置上拉加载更多
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"home_message"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    //两个按钮的父类view
    
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    //refresh按钮
    UIButton *refreshBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, 50, 50)];
    
    [rightButtonView addSubview:refreshBtn];
    
    [refreshBtn setImage:[UIImage imageNamed:@"ic_autorenew"] forState:UIControlStateNormal];
    
    [refreshBtn addTarget:self action:@selector(refreshBtnEvent) forControlEvents:UIControlEventTouchUpInside];
    refreshBtn.hidden=YES;
    
    //提交按钮
    
    UIButton *mainAndSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
    
    [rightButtonView addSubview:mainAndSearchBtn];
    
    [mainAndSearchBtn setImage:[UIImage imageNamed:@"overflow_icon"] forState:UIControlStateNormal];
    
    [mainAndSearchBtn addTarget:self action:@selector(mainAndSearchBtnEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //把右侧的两个按钮添加到rightBarButtonItem
    
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    if (![MySingleton sharedMySingleton].finished) {
        if (_model.executeState!=1)
            self.navigationItem.rightBarButtonItem = rightCunstomButtonView;
    }
    //扫描二维码按钮
    [self createButton];
    
    //返回
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
    
    if ([MySingleton sharedMySingleton].finished){
        [self postFinishExcptionUI];
    }

    //调本地存储
    NSArray * array = [LineDetail findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        [self.routeArray removeAllObjects];
        [self.routeArray addObjectsFromArray:array];
        
        //排序
        NSArray *sortArray = [self.routeArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            PointModel *pModel1 = obj1;
            PointModel *pModel2 = obj2;
            if ([pModel1.seq intValue] > [pModel2.seq intValue]) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if ([pModel1.seq intValue] < [pModel2.seq intValue]){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.routeArray removeAllObjects];
        self.routeArray=[NSMutableArray arrayWithArray:sortArray];
        //赋值sopuuid
        for (LineDetail* ld in array) {
            //取缓存标题问题
            self.lineLabel.text=ld.routeModelc.lineName;
            self.routeModelc=ld.routeModelc;
            _lineUuid=ld.lineUuid;
            //注意事项
            if (ld.routeModelc.guideline.length>0) {
                self.arrow.hidden=NO;
                self.helplabel.hidden=NO;
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *token = @"guideline";
                [defaults setObject:ld.routeModelc.guideline forKey:token];
                [defaults synchronize];
            }
            break;
        }
        
        [self.tableView reloadData];
    }
    else
    {
        //离线存储
        NSArray * array1 = [LineDetailOffline findWhere:@[@"offlineuuid",@"=",_model.orderTypeUuid]];
        
        NSMutableArray* Temp1=[NSMutableArray new];
        for (LineDetailOffline* model in array1) {
            if ([model.offlineuuid isEqualToString:_model.orderTypeUuid]) {
                LineDetail* aa=[LineDetail new];
                aa.lineid=model.lineid;
                aa.lineUuid=model.lineUuid;
                aa.pointUuid=model.pointUuid;
                aa.pointNum=model.pointNum;
                aa.pointName=model.pointName;
                aa.seq=model.seq;
                aa.uuid=_model.uuid;
                aa.scaned=model.scaned;
                aa.qrcode=model.qrcode;
                aa.operationTime=model.operationTime;
                aa.soprouteArray=model.soprouteArray;
                aa.routeModelc=model.routeModelc;
                aa.exceptionState=model.exceptionState;
                aa.exceptionRemark=model.exceptionRemark;
                
                [Temp1 addObject:aa];
            }
            
        }
        if (Temp1.count>0) {
            [self.routeArray removeAllObjects];
            [self.routeArray addObjectsFromArray:Temp1];
            
            //排序
            NSArray *sortArray = [self.routeArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                PointModel *pModel1 = obj1;
                PointModel *pModel2 = obj2;
                if ([pModel1.seq intValue] > [pModel2.seq intValue]) { //不使用intValue比较无效
                    return NSOrderedDescending;//降序
                }else if ([pModel1.seq intValue] < [pModel2.seq intValue]){
                    return NSOrderedAscending;//升序
                }else {
                    return NSOrderedSame;//相等
                }
                
            }];
            [self.routeArray removeAllObjects];
            self.routeArray=[NSMutableArray arrayWithArray:sortArray];
            //赋值sopuuid
            for (LineDetail* ld in Temp1) {
                _lineUuid=ld.lineUuid;
                //取缓存标题问题
                self.lineLabel.text=ld.routeModelc.lineName;
                self.routeModelc=ld.routeModelc;
                //注意事项
                if (ld.routeModelc.guideline.length>0) {
                    self.arrow.hidden=NO;
                    self.helplabel.hidden=NO;
                    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                    NSString *token = @"guideline";
                    [defaults setObject:ld.routeModelc.guideline forKey:token];
                    [defaults synchronize];
                }
                break;
            }
            
            [self.tableView reloadData];
            return;
        }
        else{
            [self postRouteUI];
        }
    }

    
}
-(void)goBack
{
//    if (_model.executeState==1)
//        [self searchAticle];
//    else
//    {
        NSArray * array = [LineDetail findWhere:@[@"uuid",@"=",_model.uuid]];
        if (array.count>0) {
            //删除lineuuid的linedetail//这里是删uuid还是lineuuid???
            for (LineDetail* pm in array) {
                [LineDetail deleteWhere:@[@"uuid",@"=",_model.uuid,@"lineUuid",@"=",_lineUuid]];
            }
        }
        //非空判断
//        if (![MySingleton sharedMySingleton].finished)
//        {
//            for (LineDetail* ld in self.routeArray) {
//                if (!ld.operationTime) {
//                    if (!ld.exceptionState) {
//                        
//                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                        [alert show];
//                        return;
//                    }
//                }
//                if (!ld.soprouteArray) {
//                    
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"sop未提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                        [alert show];
//                        
//                    });
//                    return;
//                }
//            }
//        }
        //存数据库
        for (LineDetail* ld in self.routeArray) {
            [ld saveOrUpdateAsync:^(BOOL isSuccess) {
                
            }];
        }
    _model.lines=self.routeArray;

        [self.rt_navigationController popViewControllerAnimated:YES];
//    }
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

-(void)sure{
    //非空判断
    if (![MySingleton sharedMySingleton].finished)
    {
        for (LineDetail* ld in self.routeArray) {
            if (!ld.operationTime) {
                if (!ld.exceptionState) {
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                    return;
                }
            }
            
                    if (!ld.soprouteArray&&!ld.exceptionState) {
            
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                            [alert show];
            
                        });
                        return;
                    }
        }
    }
    
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"确认提交工单" btnTitles:@[@"取消", @"确定"] des:@"确认提交工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
}
-(void)searchAticle{
    if (_model.executeState==1||_model.executeState==2) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"已提交的工单不能再次提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSArray * array = [LineDetail findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        //删除lineuuid的linedetail//这里是删uuid还是lineuuid???
        for (LineDetail* pm in array) {
            [LineDetail deleteWhere:@[@"uuid",@"=",_model.uuid,@"lineUuid",@"=",_lineUuid]];
        }
    }
    //非空判断
    if (![MySingleton sharedMySingleton].finished)
    {
    for (LineDetail* ld in self.routeArray) {
        if (!ld.operationTime) {
            if (!ld.exceptionState) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                return;
            }
        }
//        if (!ld.soprouteArray) {
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"sop未完成" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                [alert show];
//
//            });
//            return;
//        }
    }
    }
    //存数据库
    for (LineDetail* ld in self.routeArray) {
        [ld saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    }
    _model.lines=self.routeArray;
    if (self.block) {
        self.block(_model.uuid, self.routeArray);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
}
-(void)SopToRouteTranfer:(NSArray*) sopArr pointNum:(NSString*)pNum
{
    //此次替换，直接和sopviewcontroller里面一样新建也行
    for (int i=0; i<self.routeArray.count; i++) {
        LineDetail* line=(LineDetail*)[self.routeArray objectAtIndex:i];
        if ([line.pointNum isEqualToString:pNum]) {
            line.soprouteArray=sopArr;
            [self.routeArray replaceObjectAtIndex:i withObject:line];
            
        }
    }

    [self.tableView reloadData];
//    self.soprouteArray=sopArr;
}
//直接提交问题
-(void)SopToRouteTranfer1:(NSArray*) sopArr pointNum:(NSString*)pNum
{
    //此次替换，直接和sopviewcontroller里面一样新建也行
    for (int i=0; i<self.routeArray.count; i++) {
        LineDetail* line=(LineDetail*)[self.routeArray objectAtIndex:i];
        //直接提交问题
        NSDate* now = [NSDate date];
        NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString* dateString = [fmt stringFromDate:now];
        NSLog(@"%@", dateString);
        line.operationTime=dateString;
        
        if ([line.pointNum isEqualToString:pNum]) {
            line.soprouteArray=sopArr;
            [self.routeArray replaceObjectAtIndex:i withObject:line];
            
        }
    }
    
    //    self.soprouteArray=sopArr;
}

-(void)qrcodeTranfer:(NSString*)pNum;
{
    for (int i=0; i<self.routeArray.count; i++) {
        LineDetail* line=(LineDetail*)[self.routeArray objectAtIndex:i];
        if ([line.seq isEqualToString:pNum]) {
            line.scaned=YES;
            [self.routeArray replaceObjectAtIndex:i withObject:line];
            
        }
    }
    [self.tableView reloadData];
}
-(void)postRouteUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectLineRecords"] params:nil success:^(id responseObj) {
        NSLog(@"");

                for (NSDictionary* route in responseObj[@"content"]) {
                    RouteModel* r=[RouteModel mj_objectWithKeyValues:route];
                    
                    if ([_model.orderTypeUuid isEqualToString:r.uuid]) {

                    for (NSDictionary* line in r.details) {
                        LineDetail* l=[LineDetail mj_objectWithKeyValues:line];
                        //lineUuid居然在上面一级的model里面
                        l.lineUuid=r.uuid;
                        _lineUuid=r.uuid;
                        //不知这里为啥用了linedetail的uuid
                        l.uuid=_model.uuid;
                        l.routeModelc=r;
                        [self.routeArray addObject:l];

                        NSLog(@"");
                    }
                    self.lineLabel.text=r.lineName;
                        self.routeModelc=r;
                    }
                    //离线存储
                    for (NSDictionary* line in r.details) {
                        LineDetailOffline* l=[LineDetailOffline mj_objectWithKeyValues:line];
                        //lineUuid居然在上面一级的model里面
                        l.lineUuid=r.uuid;
                        //不知这里为啥用了linedetail的uuid
                        l.offlineuuid=r.uuid;
                        l.routeModelc=r;
                        [l saveOrUpdateAsync:^(BOOL isSuccess) {
                            
                        }];
                        NSLog(@"");
                    }

                }

        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}

-(void)postSubmitUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectLineRecords/%@",s.uuid] params:nil success:^(id responseObj) {

        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
//gcd
-(void)gcdpost
{
    NSMutableArray* t=[NSMutableArray new];
    for (WorkOrderModel* m in self.orderCopy) {
        if (m.executeState==1&&m.workOrderType==0) {
            [t addObject:m];
        }
        if (m.executeState==2&&m.workOrderType==0) {
            [t addObject:m];
        }
    }
    [MySingleton sharedMySingleton].totalCount=[MySingleton sharedMySingleton].totalCount+t.count;
    if (t.count==0) {
        return;
    }
//    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];

    WorkOrderModel* m=(WorkOrderModel*)t[0];
    NSBlockOperation* op=[NSBlockOperation blockOperationWithBlock:^{
        [self postSubmitLineUI:m];
    }];
    for (int i=1; i<t.count; i++) {
        [op addExecutionBlock:^{
            [self postSubmitLineUI:(WorkOrderModel*)t[i]];
        }];
    }
    [op start];
}
-(void)postSubmitLineUI:(WorkOrderModel*) m{
    if (m.executeState==2) {
        [self postSubmitLineUIreject:m];
        return;
    }
    //时间问题
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    
    theDate = nowDate;
    NSString* workStart=[self eightHour:theDate];
    m.workEndDate=workStart;
    if (!m.workStartDate) {
        m.workStartDate=workStart;
//        dispatch_async(dispatch_get_main_queue(), ^{
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请到任务详情重新提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
//
//        });
//        return;
    }
    //组织发送数据
    contentListLine* cl=[[contentListLine alloc] init];
    
//    cl.lineUuid=self.routeModelc.uuid;
//    cl.lineNum=self.routeModelc.lineNum;
//    cl.lineName=self.routeModelc.lineName;
    //添加站点数据
    NSMutableArray* contentCl=[NSMutableArray new];
    for (LineDetail* point in m.lines) {
        cl.lineUuid=point.routeModelc.uuid;
        cl.lineNum=point.routeModelc.lineNum;
        cl.lineName=point.routeModelc.lineName;
        
        pointList* pl=[[pointList alloc] init];
        pl.pointUuid=point.pointUuid;
        pl.pointNum=point.pointNum;
        if (!point.operationTime) {
            if (!point.exceptionState) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
            }
        }
        pl.pointName=point.pointName;
        pl.operationTime=point.operationTime;
        if (point.exceptionState)
            pl.exceptionState=point.exceptionState;
        else
            pl.exceptionState=@"0";
        if (point.exceptionRemark)
            pl.exceptionRemark=point.exceptionRemark;
        else
            pl.exceptionRemark=@"";
        if (point.scaned) {//
            pl.exceptionState=@"0";
            pl.exceptionRemark=@"";
        }
        pl.seq=point.seq;
        //添加sop
        NSMutableArray* contentPl=[NSMutableArray new];
        for (PointModel* model in point.soprouteArray) {
            //去除乱码
                    if ([model.content hasPrefix:@"[{"]) {
                        if (model.valueArr.count>0) {
                        PointValueModel* a=model.valueArr[0];
                        model.content=a.value;
                        }
                    }
                    if ([model.content isEqualToString:@"[]"]) {
                        model.content=@"";
                    }
            
            sopList* sl=[[sopList alloc] init];
            sl.templateUuid=model.sopUuid;
            sl.title=model.title;
            sl.type=model.type;
            sl.content=model.content;
            if ([self getDuplicateSubStrCountInCompleteStr:sl.content withSubStr:@"-"]>2) {
                NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",sl.content]];
                if (pic.count>0) {
                    pictureData* pd=[pic objectAtIndex:0];
                    if (pd.picurl) {
                        sl.content=pd.picurl;
                    }
                    NSMutableString* uu=[NSMutableString new];
                    if (pd.multi.count>1) {
                        for (int i=0; i<pd.multi.count; i++) {
                            NSArray* pics=[pictureData findWhere:@[@"picuuid",@"=",[pd.multi objectForKey:[NSString stringWithFormat:@"%i",i]]]];
                            if (pics.count>0) {
                                pictureData* pds=[pics objectAtIndex:0];
                                
                                [uu appendString:pds.picurl];
                                if (i!=pd.multi.count)
                                    [uu appendString:@","];
                            }
                            
                        }
                        if ([uu hasSuffix:@","]) {
                            uu=[self removeLastOneChar:uu];
                        }
                        sl.content=uu;
                    }
                }
            }
            if ([model.content isEqualToString:@""]) {
                sl.content=@"正常";
            }
            if ([model.type isEqualToString:@"picture"]) {
                if ([sl.content isEqualToString:@"正常"]) {
                    sl.content=@"";
                }
            }
            sl.remark=model.remark;
            sl.picture=model.picture;
            if ([self getDuplicateSubStrCountInCompleteStr:sl.picture withSubStr:@"-"]>2) {
                NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",sl.picture]];
                if (pic.count>0) {
                    pictureData* pd=[pic objectAtIndex:0];
                    if (pd.picurl) {
                        sl.picture=pd.picurl;
                    }
                    NSMutableString* uu=[NSMutableString new];
                    if (pd.multi.count>1) {
                        for (int i=0; i<pd.multi.count; i++) {
                            NSArray* pics=[pictureData findWhere:@[@"picuuid",@"=",[pd.multi objectForKey:[NSString stringWithFormat:@"%i",i]]]];
                            if (pics.count>0) {
                                pictureData* pds=[pics objectAtIndex:0];
                                
                                [uu appendString:pds.picurl];
                                if (i!=pd.multi.count)
                                    [uu appendString:@","];
                            }
                            
                        }
                        if ([uu hasSuffix:@","]) {
                            uu=[self removeLastOneChar:uu];
                        }
                        sl.picture=uu;
                    }
                    
                }
            }
            sl.seq=model.seq;
            [contentPl addObject:sl];
            
        }
        NSArray *dictArrayPl = [contentListLine mj_keyValuesArrayWithObjectArray:contentPl];
        pl.sopList=dictArrayPl;
        [contentCl addObject:pl];
    }
    
    NSArray *dictArrayCl = [contentListLine mj_keyValuesArrayWithObjectArray:contentCl];
    cl.pointList=dictArrayCl;

    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    [content addObject:cl];
    NSArray *dictArray = [contentListLine mj_keyValuesArrayWithObjectArray:content];
    
    if (!m.workOrderRemark)
        m.workOrderRemark=@"test";
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @1,
                             @"workStartDate" : m.workStartDate,
                             @"workEndDate" : m.workEndDate,
                             @"contentList" : cl.mj_JSONString
                             
                             };
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        WorkOrderModel* model=m;
        model.executeState=1;
//        [model saveOrUpdateAsync:^(BOOL isSuccess) {
//            NSLog(@"");
//
//        }];
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];

//        [self.rt_navigationController popViewControllerAnimated:YES];
        [MySingleton sharedMySingleton].succCount++;

        
    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        NSLog(@"");
    }];
}

-(void)refreshBtnEvent{
    
}
-(void)mainAndSearchBtnEvent{
    [self clickEvent];
}
-(void)clickEvent{
    if (_model.executeState==1) {
        return;
    }
//    [self postPhoto];
///////////////
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               if (index==0) {
                                                                   _okSubmit=NO;
                                                                   [self rejectSOP];
                                                               }
                                                               else
                                                               {
                                                                   _okSubmit=YES;
                                                                   [self sure];
//                                                                   [self postSubmitLineUI];
//                                                                   [self submitSOP];
                                                               }
                                                           }];
}
- (NSArray *) titles {
    return @[@"拒绝",@"提交"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
-(void)submitSOP
{
//    [self postSubmitLineUI];
//    [self postSubmitUI];
}
-(void)rejectSOP
{
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"拒绝工单" btnTitles:@[@"取消", @"确定"] des:@"确认拒绝工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
}
#pragma mark -
- (void)xt_alertViewControllerClickIndex:(NSInteger)buttonIndex remark:(NSString *)rem
{
    self.refuseRemark=rem;
    if (_okSubmit) {
        switch (buttonIndex) {
            case 0:
                NSLog(@"0");
                NSLog(@"Cancel");
                break;
            case 1:
                NSLog(@"1");
                NSLog(@"Determine");
                [MySingleton sharedMySingleton].reject=NO;
                [self searchAticle];
                break;
            case 2:
                NSLog(@"2");
                NSLog(@"summerxx");
                break;
            default:
                break;
        }
    }
    else{
    switch (buttonIndex) {
        case 0:
            NSLog(@"0");
            NSLog(@"Cancel");
            break;
        case 1:
            NSLog(@"1");
            NSLog(@"Determine");
            [MySingleton sharedMySingleton].reject=YES;
            [self postSubmitLineUIrejectEvent];
            break;
        case 2:
            NSLog(@"2");
            NSLog(@"summerxx");
            break;
        default:
            break;
    }
    }
}

-(void)rightBarButtonItemClick
{
//    lhScanQCodeViewController * sqVC = [[lhScanQCodeViewController alloc]init];
//    //    UINavigationController * nVC = [[UINavigationController alloc]initWithRootViewController:sqVC];
//    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:sqVC];
//    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:nav animated:YES completion:^{
//        NSLog(@"%@");
//    }];
//    sqVC.block = ^{
//        int scanline=0;
//        for (int i=0; i<self.routeArray.count; i++) {
//            LineDetail* line=(LineDetail*)[self.routeArray objectAtIndex:i];
//            if ([line.qrcode isEqualToString:[MySingleton sharedMySingleton].QRcode]) {
//                line.scaned=YES;
//                //扫描时间
//                NSDate* now = [NSDate date];
//                NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
//                fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
//                fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//                NSString* dateString = [fmt stringFromDate:now];
//                NSLog(@"%@", dateString);
//                line.operationTime=dateString;
//                
//                scanline=i;
//                [self.routeArray replaceObjectAtIndex:i withObject:line];
//                
//            }
//        }
//        [self.tableView reloadData];
//        //自动滚动到扫描行
//        NSIndexPath * dayOne = [NSIndexPath indexPathForRow:scanline inSection:0];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
//
//        });
//    };
    
    MyBarCodeController *ctrl = [[MyBarCodeController alloc] initWithNibName:@"MyBarCodeController" bundle:nil];
    ctrl.pageType = MyBarCodeControllerPageTypeScan;
    RTRootNavigationController *nav1 = [[RTRootNavigationController alloc] initWithRootViewController:ctrl];
    nav1.title = @"扫一扫";
    [self presentViewController:nav1 animated:YES completion:nil];
    ctrl.block = ^{
        int scanline=0;
        int qrfit=0;//没有匹配
        for (int i=0; i<self.routeArray.count; i++) {
            LineDetail* line=(LineDetail*)[self.routeArray objectAtIndex:i];
            if ([line.qrcode isEqualToString:[MySingleton sharedMySingleton].QRcode]) {
                line.scaned=YES;
                qrfit++;
                //扫描时间
                NSDate* now = [NSDate date];
                NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
                fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
                fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                NSString* dateString = [fmt stringFromDate:now];
                NSLog(@"%@", dateString);
                line.operationTime=dateString;
                //开始时间设置为第一次扫码的时间
                //时间问题
                NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
                [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
                
                
                NSDate*nowDate = [NSDate date];
                NSDate* theDate;
                
                
                theDate = nowDate;
                NSString* workStart=[self eightHour:theDate];
                if (!_model.workStartDate)
                    _model.workStartDate=workStart;
                
                scanline=i;
                [self.routeArray replaceObjectAtIndex:i withObject:line];
                //
                //直接进sop
                SopViewController * detailVC = [[SopViewController alloc]init];
                detailVC.workModel = _model;
                [self.rt_navigationController pushViewController:detailVC animated:YES];
                detailVC.line=[self.routeArray objectAtIndex:i];
                detailVC.delegate=self;//sop传回路线sop数据
                //qrfit放在后面，改了直接进sop

            }
        }
        if (qrfit==0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"二维码与检查点不匹配" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
//        [self.tableView reloadData];
//        //自动滚动到扫描行
//        NSIndexPath * dayOne = [NSIndexPath indexPathForRow:scanline inSection:0];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
//
//        });
        
    };
}

- (void)createButton{
    
    _window = [UIApplication sharedApplication].windows[0];
    
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_button setTitle:@"xxx" forState:UIControlStateNormal];
    
    _button.frame = CGRectMake(self.view.bounds.size.width /2-70, self.view.bounds.size.height - 200, 140, 60);
    
    _button.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    
//    [_button setBackgroundColor:DGColor];
    
    _button.layer.cornerRadius = 30;
    
    _button.layer.masksToBounds = YES;
    
    [_button addTarget:self action:@selector(resignButton) forControlEvents:UIControlEventTouchUpInside];
//
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    UIColor *color1=[UIColor colorWithHexString:@"#FE962C" alpha:1];
//    UIColor *color2=[UIColor colorWithHexString:@"#FF0000" alpha:1];
//    gradientLayer.colors = @[(__bridge id)color1.CGColor, (__bridge id)color2.CGColor];
//    gradientLayer.locations = @[@0.5, @1.0];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1.0, 0);
//    gradientLayer.bounds = CGRectMake(0, 0, 140*2, 60*2);
//    [_button.layer addSublayer:gradientLayer];
    
    [_button setImage:[UIImage imageNamed:@"QR button"] forState:UIControlStateNormal];
    
    [self.view addSubview:_button];
//    UIImageView* scan=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"route_scan"]];
//    [_button addSubview:scan];
    
//    [scan mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.mas_equalTo(_button).offset(0);
//        make.width.mas_equalTo(@30);
//        make.height.mas_equalTo(@30);
//
//    }];
    //    [_window makeKeyAndVisible];//显示window
    
    //放一个拖动手势，用来改变控件的位置
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)];
    
    [_button addGestureRecognizer:pan];
    
}

- (void)resignButton{
    [self rightBarButtonItemClick];
}

//手势事件 －－ 改变位置

-(void)changePostion:(UIPanGestureRecognizer *)pan{
    
    CGPoint point = [pan translationInView:_button];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    CGRect originalFrame = _button.frame;
    
    if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) {
        
        originalFrame.origin.x += point.x;
        
    }if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) {
        
        originalFrame.origin.y += point.y;
        
    }
    
    _button.frame = originalFrame;
    
    [pan setTranslation:CGPointZero inView:_button];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        _button.enabled = NO;
        
    }else if (pan.state == UIGestureRecognizerStateChanged){
        
    } else {
        
        CGRect frame = _button.frame;
        
        //是否越界
        
        BOOL isOver = NO;
        
        if (frame.origin.x < 0) {
            
            frame.origin.x = 0;
            
            isOver = YES;
            
        } else if (frame.origin.x+frame.size.width > width) {
            
            frame.origin.x = width - frame.size.width;
            
            isOver = YES;
            
        }if (frame.origin.y < 0) {
            
            frame.origin.y = 0;
            
            isOver = YES;
            
        } else if (frame.origin.y+frame.size.height > height) {
            
            frame.origin.y = height - frame.size.height;
            
            isOver = YES;
            
        }if (isOver) {
            
            [UIView animateWithDuration:0.3 animations:^{
                
                _button.frame = frame;
                
            }];
            
        }
        
        _button.enabled = YES;
        
    }
    
}
- (void)lineSelectedAtIndex:(LineDetail*)index
{
//    for (int i=0;i<self.routeArray.count;i++)
//    {
//        LineDetail* point=[self.routeArray objectAtIndex:i];
//        if ([point.pointNum isEqualToString:index.pointNum]) {
//            [self.routeArray replaceObjectAtIndex:1 withObject:index];
//        }
//    }
    NSMutableArray* sopTemp=[NSMutableArray new];
    for (LineDetail* model in self.routeArray) {
        if ([model.pointNum isEqualToString:index.pointNum]) {
            [sopTemp addObject:index];
        }
        else
            [sopTemp addObject:model];
    }
    [self.routeArray removeAllObjects];
    self.routeArray=sopTemp;
    [self.tableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.routeArray.count;
//    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RouteViewCell* cell=[RouteViewCell cellWithTableView:tableView];
    RouteModel* model=[RouteModel new];
    model.ID=indexPath.row;
    model.details=self.routeArray;
    if ([MySingleton sharedMySingleton].finished) {
        model.excepDetails=self.exceptionArray;
//        if (self.exceptionArray.count>0) {
//            cell.scanView.lineF =[self.exceptionArray objectAtIndex:indexPath.row];
//
//        }

    }
    cell.model=model;
    LineDetail* scan=(LineDetail*)[self.routeArray objectAtIndex:indexPath.row];


    if (scan.scaned) {
        cell.scanView.hidden=NO;
        //扫描成功变灰色
        [cell.remarkView.remarkLabel1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    cell.block = ^{
         if (scan.exceptionState&&[scan.exceptionState isEqualToString:@"1"]) {
             if (!scan.scaned) {
                 return;
             }
        }
        if (!scan.scaned) {
            if (![MySingleton sharedMySingleton].finished) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"请扫描检查点的二维码或备注以提交巡逻表格" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
            }
        }
            [cell.remarkView.remarkLabel1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        SopViewController * detailVC = [[SopViewController alloc]init];
        detailVC.workModel = _model;
        [self.rt_navigationController pushViewController:detailVC animated:YES];
        detailVC.line=[self.routeArray objectAtIndex:indexPath.row];
        detailVC.delegate=self;//sop传回路线sop数据
    };
    cell.blockError = ^{
        if (scan.scaned) {
            return;
        }
        //异常状态人口
        DetailViewController * detailVC = [[DetailViewController alloc]init];
        detailVC.line=[self.routeArray objectAtIndex:indexPath.row];
        if ([MySingleton sharedMySingleton].finished) {
            if (self.exceptionArray.count>0) {
                detailVC.line=[self.exceptionArray objectAtIndex:indexPath.row];
            }
        }
        detailVC.workModel = _model;


        detailVC.delegate=self;
        //    detailVC.model = self.aticleArray[indexPath.row];
        [self.rt_navigationController pushViewController:detailVC animated:YES];
        
        //时间问题
        NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
        [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
        
        
        NSDate*nowDate = [NSDate date];
        NSDate* theDate;
        
        
        theDate = nowDate;
        NSString* workStart=[self eightHour:theDate];
        //开始时间设置为第一次扫码的时间
        if (!_model.workStartDate)
            _model.workStartDate=workStart;
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    AticleModel * model = self.aticleArray[indexPath.row];
//    if (model.ViewType == 1) {
//        return [HomeBaseCell heightWithModel:model];
//        
//    }else if (model.ViewType == 2) {
//        return [HomeOneImageCell heightWithModel:model];
//        
//    }else if (model.ViewType == 3){
//        return [NewsMoreImageCell heightWithModel:model];
//    }else if (model.ViewType == 4){
//        return [HomeOneImageCell heightWithModel:model];
//    }
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
     NewsDetailViewController * detailVC = [[NewsDetailViewController alloc]init];
     detailVC.model = self.aticleArray[indexPath.row];
     [self.rt_navigationController pushViewController:detailVC animated:YES];
     */
//    SopViewController * detailVC = [[SopViewController alloc]init];
//    //    detailVC.model = self.aticleArray[indexPath.row];
//    [self.rt_navigationController pushViewController:detailVC animated:YES];
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        view.backgroundColor = XMColor(241, 245, 247);
        UILabel* titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont xm_medium:17.0];
        titleLabel.numberOfLines = 1;
        titleLabel.textColor = [UIColor xm_jetblackColor];
        titleLabel.text=@"巡检路线";
        
        [view addSubview:titleLabel];
        self.lineLabel=titleLabel;
        
        UIImageView* arrow=[[UIImageView alloc] init];
        [arrow setImage:[UIImage imageNamed:@"arrow"]];
        [view addSubview:arrow];
        
        UILabel* helpLabel = [[UILabel alloc]init];
        helpLabel.font = [UIFont xm_medium:17.0];
        helpLabel.numberOfLines = 1;
        helpLabel.textColor = [UIColor xm_jetblackColor];
        helpLabel.text=@"注意事项";
        
        [view addSubview:helpLabel];
        //注意事项没有就不显示
        arrow.hidden=YES;
        helpLabel.hidden=YES;
        self.arrow=arrow;
        self.helplabel=helpLabel;
        tableView.tableHeaderView=view;
        
        UIView * viewFoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
        viewFoot.backgroundColor = [UIColor whiteColor];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        button.frame = CGRectMake(40, 100, SCREEN_WIDTH- 80, 30);
        button.backgroundColor = DGColor;
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitRoute) forControlEvents:UIControlEventTouchUpInside];
        [viewFoot addSubview:button];
//        tableView.tableFooterView=viewFoot;
        //        [button setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
        //        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.left.equalTo(view.mas_left).offset(20);
        }];
        
        [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(helpLabel).offset(0);
            make.right.equalTo(view.mas_right).offset(-38);
            make.height.mas_equalTo(@16);
            make.width.mas_equalTo(@8);
        }];
        [helpLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.right.equalTo(arrow.mas_left).offset(-5);
        }];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(viewFoot).offset(0);
            //            make.top.equalTo(view).offset(5);
            make.width.mas_equalTo(SCREEN_WIDTH-80);
            make.height.mas_equalTo(50);
            //            make.left.equalTo(view.mas_left).offset(20);
        }];
        _tableView = tableView;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
        [view addGestureRecognizer:tapGesture];
    }
    return _tableView;
}
-(void)submitRoute
{
    
}
-(void)tapGestureRecognizer{
    if (self.helplabel.hidden) {
        return;
    }
    SopNoticeViewController* detailVC = [[SopNoticeViewController alloc]init];
    //    detailVC.model = self.aticleArray[indexPath.row];
    [self.rt_navigationController pushViewController:detailVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)postSubmitLineUIrejectEvent
{
    if ([self.refuseRemark isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请填写拒绝原因" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSArray * array = [LineDetail findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        //删除lineuuid的linedetail//这里是删uuid还是lineuuid???
        for (LineDetail* pm in array) {
            [LineDetail deleteWhere:@[@"uuid",@"=",_model.uuid]];
        }
    }
    //存数据库
    for (LineDetail* ld in self.routeArray) {
        [ld saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    }
    _model.lines=self.routeArray;
    if (self.block) {
        self.block(_model.uuid, self.routeArray);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
}

-(void)postSubmitLineUIreject:(WorkOrderModel*) m{
    //组织发送数据
    contentListLine* cl=[[contentListLine alloc] init];
    
//    cl.lineUuid=self.routeModelc.uuid;
//    cl.lineNum=self.routeModelc.lineNum;
//    cl.lineName=self.routeModelc.lineName;
    //添加站点数据
    NSMutableArray* contentCl=[NSMutableArray new];
    for (LineDetail* point in m.lines) {
        
        pointList* pl=[[pointList alloc] init];
        pl.pointUuid=point.pointUuid;
        pl.pointNum=point.pointNum;
        pl.pointName=point.pointName;
        
        NSDate* now = [NSDate date];
        NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString* dateString = [fmt stringFromDate:now];
        NSLog(@"%@", dateString);
        pl.operationTime=dateString;
        
        pl.seq=point.seq;
        //添加sop
        NSMutableArray* contentPl=[NSMutableArray new];
        for (PointModel* model in point.soprouteArray) {
            
            sopList* sl=[[sopList alloc] init];
            sl.templateUuid=model.sopUuid;
            sl.title=model.title;
            sl.type=model.type;
            sl.content=model.content;
            if ([model.content isEqualToString:@""]) {
                sl.content=@"正常";
            }
            sl.remark=model.remark;
            sl.picture=model.picture;
            sl.seq=model.seq;
            [contentPl addObject:sl];
            
        }
        NSArray *dictArrayPl = [contentListLine mj_keyValuesArrayWithObjectArray:contentPl];
        pl.sopList=dictArrayPl;
        [contentCl addObject:pl];
    }
    
    NSArray *dictArrayCl = [contentListLine mj_keyValuesArrayWithObjectArray:contentCl];
    cl.pointList=dictArrayCl;
    
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    [content addObject:cl];
    NSArray *dictArray = [contentListLine mj_keyValuesArrayWithObjectArray:content];
    
    if (!m.workOrderRemark)
        m.workOrderRemark=@"test";
    if (!self.refuseRemark) {
        self.refuseRemark=@"拒绝";
    }
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @2,
                             @"count" : @(self.rejectCount),
                             @"refuseRemark" : self.refuseRemark
                             
                             };
    
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        WorkOrderModel* model=self.model;
        model.executeState=2;
        _rejectCount++;
        _model.executeState=[@"2" integerValue];
//        HomeViewController * homeVC = [[HomeViewController alloc]init];
//        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
//        // 添加为子控制器
//        nav.title = @"任务箱";
//        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
//        if (self.blockReject) {
//            self.blockReject();
//        }

//        [model saveOrUpdateAsync:^(BOOL isSuccess) {
//            NSLog(@"");
//
//        }];
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;
        
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rt_navigationController popViewControllerAnimated:YES];
        });
    }];
}
 //保安队长已完成，异常备注
-(void)postFinishExcptionUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"uuid" : _model.uuid,
                             @"workOrderType" : @(_model.workOrderType)
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:[NSString stringWithFormat:@"digiops/app/workOrder/SelectFindById"] params:params success:^(id responseObj) {
        NSLog(@"");
        if (responseObj[@"content"]==[NSNull null]) {
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            return;
        }
        [self.exceptionArray removeAllObjects];
        for (NSDictionary* shift in responseObj[@"content"]) {
            LineDetail* s=[LineDetail mj_objectWithKeyValues:shift];
            [self.exceptionArray addObject:s];
            NSLog(@"");
////            if ([self.line.pointNum isEqualToString:s.pointName]) {
//
//                for (NSDictionary* shift1 in shift[@"recordContents"]) {
//
//                    PointModel* a=[PointModel mj_objectWithKeyValues:shift1];
//                    if ([a.templateUuid isEqualToString:s.sopUuid]) {
//
//                        //                    p.shiftUuid=a.uuid;
////                        [self.sopArray addObject:a];
//                    }
//                }
////            }
            
        }
        [self.tableView reloadData];
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
@end
